<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Db;

class User Extends Base
{
	protected $id = 'user_id';
	protected $table = 'user';
	protected $join = ['role r','m.role_id = r.role_id','left'];
	protected $field = 'm.*,r.role_name';
	
	protected function search() {
		
		$where = [];
		$role = input('param.role_id');
		$filter = input('param.filter');
		
		$role &&  $where['m.role_id'] = $role;
		$filter == 'delete' && $where['m.delete_time'] = ['>',0];
		
		return $where;
		
	}
	
	protected function validData($data = []) {
		
		//分
		$where = $data[$this->id] ? [$this->id=> ['<>',$data[$this->id] ]] : [];
		$repeat = Db::name('user')->where($where)->whereNull('delete_time')->where(function($query) use($data) {
			$query->whereOr('username',$data['username'])->whereOr('mobile',$data['mobile']);
		})->fetchSql(0)->find();
		
		if($repeat) {
			$msg = $repeat['username'] == $data['username'] ? '用户名已经存在' : '手机号已经存在';
			return $this->error($msg);
		}
	}
	
	
	protected function parseData($data = []) {
		
		
		if($data['password']) {
			$data['salt'] = substr(uniqid(), -6);
			$data['password'] = CorePwd($data['password'],$data['salt']);	
		}
		
		return $data;
	}
	
	protected function options($item = []) {
		
		$roles = Db::name('role')->whereNull('delete_time')->column('role_name','role_id');
		$this->assign('roles',$roles);
		$this->assign('role_ids',TplOptions($roles,$item['role_id']));
		
		return $item;
		
	}	
    
}
